package cn.edu.ahtcm.file;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class TestFile {

    public static void main(String[] args) {
        // 创建文件夹
        //windows 操作系统
        //Path mydirectory = Paths.get("D:\\test\\myjava");
        //Linux 操作系统
        Path mydirectory = Paths.get("/Users/hufox/testdirectory");
        if(!Files.exists(mydirectory)){
            try {
                Files.createDirectories(mydirectory);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //创建文件
        //Path file = Paths.get("D:\\test\\myjava\\hello.txt");
        Path file = Paths.get("/Users/hufox/testdirectory/hello.txt");
        if(!Files.exists(file)){
            try {
                Files.createFile(file);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //写文件
        FileOutputStream fs = null;
        try {
            //fs = new FileOutputStream("D:\\test\\myjava\\hello.txt");
            fs = new FileOutputStream("/Users/hufox/testdirectory/hello.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            StringBuffer sb = new StringBuffer("hello world\r\n");
            sb.append("hello java");
            fs.write(sb.toString().getBytes());
            fs.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //读文件
        try {
            BufferedReader br = Files.newBufferedReader(file);
            String str = null;
            while((str = br.readLine())!=null){
                System.out.println(str);
            }
            br.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //删除文件
        if(Files.exists(file)){
            try {
                Files.delete(file);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }

}
